# -*- coding: utf-8 -*-

from odoo import models, fields, api,_


# class e(models.Model):
#     _name = 'sea.sale.pricing.order'
from odoo.exceptions import UserError


class SalePricingOrder(models.Model):
    _name = 'sale.pricing.order'
    _description = u'销售核价单'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin', 'base.approve']

    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'sale.pricing.order')])
    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'sale.pricing.order')])
    revise_date = fields.Date()
    name = fields.Char()
    partner_id = fields.Many2one('res.partner', ondelete='restrict', string=u'客户', requierd=1)
    date = fields.Date(default=fields.Date.today, string=u'单据日期')

    amount_total = fields.Float(compute='compute_amount_total')

    def compute_amount_total(self):
        for r in self:
            r.amount_total = sum(line.price_unit for line in r.line_ids)

    def get_default_department_id(self):
        if self.env.user.employee_ids:
            return self.env.user.employee_ids[0].department_id.id

    department_id = fields.Many2one('hr.department', ondelete='restrict', string='部门',
                                    default=get_default_department_id)
    user_id = fields.Many2one('res.users', default=lambda self: self.env.user)
    # revise_uid=fields.Many2one('res.users')
    line_ids = fields.One2many('sale.pricing.order.line', 'order_id')
    # state=fields.Selection([
    #     ('draft','草稿'),
    #     ('done', '完成'),
    # ])
    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)

    def check_values(self):
        if not self.line_ids:
            raise UserError('明细行必填')
        return super(SalePricingOrder, self).check_values()

    @api.model
    def create(self, vals):
        if not vals.get('name') or vals['name'] == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('sale.pricing.order') or _('New')
        return super(SalePricingOrder, self).create(vals)


class SalePricingOrderLine(models.Model):
    """
            INTEGER,	项次
        VARCHAR2(30 BYTE),	料号
        VARCHAR2(30 BYTE),	厂商料号
        VARCHAR2(4 BYTE),	币别
        NUMBER(16,6),	原未税单价
        NUMBER(16,6),	新未税单价
        DATE,	原核价日期
        DATE	新核价日期

    """
    _name = 'sale.pricing.order.line'
    _description = u'销售核价单明细'
    _order = 'sequence'
    sequence = fields.Integer(default=10)
    order_id = fields.Many2one('sale.pricing.order', ondelete='cascade')
    partner_id = fields.Many2one('res.partner', related='order_id.partner_id', store=True)
    product_id = fields.Many2one('product.product',required=1)
    old_price_unit = fields.Float(string=u'旧单价',digits='Product Price')
    price_unit = fields.Float(string=u'单价',digits='Product Price')
    vendor_code = fields.Char(string='客户码')
    department_id = fields.Many2one('hr.department', related='order_id.department_id', store=True)
    old_date = fields.Date(string=u'原核价日期')
    new_date = fields.Date(string=u'新核价日期', related='order_id.date', store=True)
    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)

    def get_old_price(self, product_id):
        price_old = self.env['sale.pricing.order.line'].search([('product_id', '=', product_id.id),('state','=','done')] ,order='new_date desc',limit=1)
        if price_old:
            return price_old.price_unit,price_old.new_date

    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('rejected', u'拒绝'),
        ('done', u'完成'),
    ], string=u"状态", related='order_id.state', store=True)

    @api.onchange('product_id')
    def onchange_product_id(self):
        if self.product_id:
            code = self.env['product.partner.code'].search(
                [('partner_id', '=', self.partner_id.id), ('product_tmpl_id', '=', self.product_id.product_tmpl_id.id)],
                limit=1)
            if code:
                self.vendor_code = code[0].code
            else:
                self.vendor_code=''
            if self.get_old_price(self.product_id):
                price_unit,date=self.get_old_price(self.product_id)
                self.old_price_unit = price_unit
                self.old_date=date
